<?php
namespace app\home\controller;

use app\common\logic\UserWalletSilver as UserWalletSilverLogic;
use app\common\component\user\UserService;
use app\common\component\user_wallet_silver\UserWalletSilverModel;

class UserWalletSilver extends ControllerBase {
	public function _initialize() {
		$this -> checkLogin();
	}

	public function index() {
		$currentUserWalletSilver = (new UserWalletSilverLogic()) -> getInterest();
		$this -> view -> assign('currentUserWalletSilverPrice', $currentUserWalletSilver['data']['price']);

		$resultUserWalletSilver = UserWalletSilverModel::alias('u_w_s')
		-> join('league_user u', 'u_w_s.from_user_id = u.user_id')
		-> field(
			'u_w_s.*, ' .
			'u.username, u.realname, u.phone, u.bank_code'
		)
		-> where('u_w_s.user_id', \think\Session::get('user_id'))
		-> order('u_w_s.status ASC') -> paginate(10, true);

		$this -> view -> assign('userWalletSilvers', $resultUserWalletSilver);

		return $this -> view -> fetch();
	}

	public function withdraw() {
		$currentUserWalletSilver = (new UserWalletSilverLogic()) -> getInterest();
		if($this -> request -> isPost()) {
			$post = $this -> request -> post();

			if($post['price'] > $currentUserWalletSilver['data']['price']) {
				echo '<meta charset="utf-8"><script>alert("您没有足够的银豆提现!");window.history.go(-1);</script>';
			} else {
				$resultCheckPayPassword = (new UserService()) -> checkPayPassword($post['pay_password']);
		    	if($resultCheckPayPassword['code'] !== 0) {
		    		echo '<meta charset="utf-8"><script>alert("您输入的支付密码有误!");window.history.go(-1);</script>';exit;
		    	}

				$resultUserWalletSilverLogic = (new UserWalletSilverLogic()) -> withdraw($post['price']);
				if($resultUserWalletSilverLogic['code'] !== 0) {
		    		echo '<meta charset="utf-8"><script>alert("' . $resultUserWalletSilverLogic['message'] . '!");window.history.go(-1);</script>';exit;
		    	}

				echo '<meta charset="utf-8"><script>alert("' . $resultUserWalletSilverLogic['message'] . '!");window.location.href="/wallet/silver";</script>';exit;
			}
		}
		$this -> view -> assign('currentUserWalletSilverPrice', $currentUserWalletSilver['data']['price']);

		$resultUser = (new UserService) -> getUser();
    	$this -> view -> assign('user', $resultUser['data']['user']);

		return $this -> view -> fetch();
	}
}